package com.zzyl.nursing.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceShadowVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备表Service业务层处理
 * 
 * @author sumu
 * @date 2025-08-03
 */
@Slf4j
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper,Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IoTDAClient client;

    /**
     * 查询设备表
     *
     * @param productKey 设备表主键
     * @return 设备表
     */
    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        //调用华为云平台接口
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        //调用API
        ShowProductResponse response = client.showProduct(request);
        //解析结果集
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if(CollUtil.isEmpty(serviceCapabilities)){
            return Collections.emptyList();
        }
        return serviceCapabilities;

    }

    /**
     * 查询设备表
     *
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备表列表
     *
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     *
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        device.setCreateTime(DateUtils.getNowDate());
        return deviceMapper.insert(device);
    }


    /**
     * 修改设备表
     *
     * @param dto 设备表
     * @return 结果
     */
    @Override
    public int updateDevice(DeviceDto dto) {
        Device deviceID = deviceMapper.selectById(dto.getId());
        if (deviceID == null) {
            throw new BaseException("设备不存在");
        }
        boolean exists = deviceMapper.exists(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId())
                .eq(Device::getId, dto.getId())
                .ne(Device::getId,dto.getId()));
        if (exists) {
            throw new BaseException("设备已被使用");
        }
        //更新设备数据
        Device device = new Device();
        device.setId(dto.getId());
        device.setDeviceName(dto.getDeviceName());
        device.setBindingLocation(dto.getBindingLocation().toString());
        device.setNodeId(dto.getNodeId());
        int updateDevice = deviceMapper.updateDevice(device);
        if (updateDevice == 0) {
            throw new BaseException("更新设备失败");
        }
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(dto.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.setDeviceName(dto.getDeviceName());

        if (!ObjectUtil.equals(device.getBindingLocation(),dto.getBindingLocation())) {
            body.setExtensionInfo(device.getBindingLocation());
        }
        request.withBody(body);
        UpdateDeviceResponse response = client.updateDevice(request);

        return updateDevice;
    }



    /**
     * 批量删除设备表
     *
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteByIds(Arrays.asList(ids));
    }

    /**
     * 删除设备表信息
     *
     * @param id 设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteById(id);
    }


    @Override
    public void syncProductList() {
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = client.listProducts(request);
        List<ProductSummary> products = response.getProducts();
        if(CollUtil.isEmpty(products)){
            throw  new BaseException("物联网接口 - 查询产品，同步失败");
        }
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(products));
    }

    /***
     * 设备注册
     * @param dto
     */
    @Override
    public void registerDevice(DeviceDto dto) {
        Long deviceName = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()));
        if(deviceName>=1){
            throw new BaseException("设备已存在");
        }
        Long nodeCount = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId()));
        if(nodeCount>=1){
            throw new BaseException("设备标识已存在");
        }
        deviceMapper.selectCount(Wrappers.<Device>lambdaQuery().eq(ObjectUtil.isNotEmpty(dto.getBindingLocation()),Device::getBindingLocation,dto.getBindingLocation())
                .eq(ObjectUtil.isNotEmpty(dto.getLocationType()),Device::getLocationType,dto.getLocationType())
                .eq(ObjectUtil.isNotEmpty(dto.getProductKey()),Device::getProductKey,dto.getProductKey()));
        //调用华为云IOT平台注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        AuthInfo authInfobody = new AuthInfo();
        authInfobody
                .withSecret(UUID.randomUUID().toString().replace("-",""));
        body.withAuthInfo(authInfobody);
        body.withProductId(dto.getProductKey());
        body.withDeviceName(dto.getDeviceName());
        body.setNodeId(dto.getNodeId());
        request.withBody(body);
        //调用华为云
        AddDeviceResponse response = client.addDevice(request);
        String deviceId = response.getDeviceId();
        //将数据写到本地
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setIotId(deviceId);
        device.setSecret(authInfobody.getSecret());
        save(device);
    }

    /**
     * 查询设备详情
     *
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查询数据库
        Device device  = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if(ObjectUtil.isEmpty(device)){
            throw  new BaseException("设备不存在");
        }
        //调用华为云窗口
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        DeviceDetailVo deviceVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceVo.setDeviceStatus(response.getStatus());
        String activeTime1 = response.getActiveTime();
        if(StringUtils.isNotEmpty(activeTime1)){
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTime1, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceVo.setActiveTime(activeTime);
        }

        return deviceVo;
    }

    /**
     * 查询设备上报数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<DeviceShadowVo> queryServiceProperties(String iotId) {
        //调用华为云IOT，查询设备影子数据
        ShowDeviceShadowRequest  request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse  response = client.showDeviceShadow(request);
        //2查询不到，返回空
        List<DeviceShadowData> shadow = response.getShadow();
        if(CollUtil.isEmpty(shadow)){
            return Collections.emptyList();
        }
        //转换vo数据
        JSONObject jsonObject  = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());
        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        // 日期时区转换
        LocalDateTime eventTimeInfo = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        //封装VO
        ArrayList<DeviceShadowVo> vos = new ArrayList<>();
        jsonObject.forEach((key,vlaue)->{
            DeviceShadowVo vo = DeviceShadowVo.builder()
                    .functionId(key)
                    .value(vlaue)
                    .eventTime(eventTimeInfo)
                    .build();
            vos.add(vo);
        });
        return vos;
    }

    /**
     * 删除设备
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteDevice(String iotId) {
        // 1. 先从数据库中查询设备信息
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)) {
            return 0; // 设备不存在
        }

        // 2. 调用华为云IoTDA接口删除设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);

        try {
            DeleteDeviceResponse response = client.deleteDevice(request);
            log.info("华为云设备删除成功，设备ID: {}, 响应: {}", iotId, response.toString());
        } catch (ConnectionException e) {
            log.error("连接华为云失败，设备ID: {}", iotId, e);
            throw new BaseException("连接华为云失败");
        } catch (RequestTimeoutException e) {
            log.error("请求华为云超时，设备ID: {}", iotId, e);
            throw new BaseException("请求华为云超时");
        } catch (ServiceResponseException e) {
            log.error("华为云服务响应异常，设备ID: {}", iotId, e);
            log.error("HTTP状态码: {}", e.getHttpStatusCode());
            log.error("错误码: {}", e.getErrorCode());
            log.error("错误消息: {}", e.getErrorMsg());
            throw new BaseException("删除华为云设备失败: " + e.getErrorMsg());
        } catch (Exception e) {
            log.error("删除华为云设备时发生未知错误，设备ID: {}", iotId, e);
            throw new BaseException("删除华为云设备时发生未知错误");
        }

        // 3. 删除本地数据库记录
        int result = deviceMapper.delete(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));

        return result;
    }


//    @Transactional(rollbackFor = Exception.class)
//    @Override
//    public int deleteDevice(String iotId) {
//        // 1. 先从数据库中查询设备信息
//
//        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
//        if (ObjectUtil.isEmpty(device)) {
//            throw new BaseException("设备不存在");
//        }
//        int result = deviceMapper.delete(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
//
//        // 2. 调用华为云IoTDA接口删除设备
//        DeleteDeviceRequest request = new DeleteDeviceRequest();
//        request.setDeviceId(iotId);
//        client.deleteDevice(request);
//        return device;
//
//    }


    @Override
    public List<ProductVo> getAllProduct() {
        String jsonObject = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        if(ObjectUtil.isEmpty(jsonObject)){
            return Collections.emptyList();
        }
        return JSONUtil.toList(jsonObject,ProductVo.class);
    }


}
